package com.twm.tamauth.utils

import android.graphics.Bitmap
import android.media.Image

/**
 * 处理图片转换的方法
 */
object MyAuthImageUtils {

    /**
     * 转换图片 为 [Bitmap].
     *
     * @param image 待转换的图片.
     * @return bitmap
     */
    fun imageToBitmap(image: Image): Bitmap {
        val width = image.width
        val height = image.height
        val plane = image.planes[0]
        val buffer = plane.buffer

        // Distance between two pixels
        val pixelStride = plane.pixelStride
        // The stride of the entire row of pixels in memory
        val rowStride = plane.rowStride
        val rowPadding = rowStride - pixelStride * width

        val bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888)
        buffer.rewind() // Ensure the buffer is at its beginning
        bitmap.copyPixelsFromBuffer(buffer)
        image.close()

        return bitmap
    }
}
